<template>
    <LayoutWrap class="bill-platform">
        <el-form @submit.native.prevent ref="formSearch" :inline="true" :model="formSearch" label-width="80px">
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="关键词" prop="keyName">
                        <el-select
                            class="custom-the-select_key"
                            popper-class="custom-the-select-popper_key"
                            v-model="formSearch.keyName"
                            placeholder="请选择"
                            style="width: 105px;margin-right: 10px;"
                        >
                            <el-option
                                v-for="item in keyOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            >
                            </el-option>
                        </el-select>
                        <br v-if="isMobile" />
                        <el-input
                            v-model="formSearch.keyValue"
                            placeholder="请输入关键字检索"
                            @keyup.enter.native="getList"
                            style="width: 180px"
                        ></el-input>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="  ">
                        <el-button type="primary" style="min-width: 120px;" @click="handleSearch">查询</el-button>
                        <br v-if="isMobile" />
                        <el-button type="default" style="min-width: 120px;" @click="resetForm('formSearch')"
                            >重置</el-button
                        >
                    </el-form-item>
                </div>
            </div>
        </el-form>
        <ul v-if="isOperation" class="list-head">
            <li class="list-head-item">
                <el-button @click="onClickDetail(dataSourceDefault, '添加平台')" :disabled="!isOperation" type="primary"
                    >添加平台</el-button
                >
            </li>
        </ul>
        <el-table
            v-loading="isLoading"
            :data="tableData"
            show-summary
            :summary-method="getSummaries"
            border
            @selection-change="handleSelectionChange"
            :default-sort="{prop: 'date', order: 'descending'}"
            style="width: 100%"
        >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="name" label="平台名称"></el-table-column>
            <el-table-column prop="money_total" label="授信额度">
                <template v-slot="{row}">
                    {{ row.money_total / BASIC_MONEY }}
                </template>
            </el-table-column>
            <el-table-column prop="money_used" label="使用额度">
                <template v-slot="{row}">
                    {{ row.money_used / BASIC_MONEY }}
                </template>
            </el-table-column>
            <el-table-column prop="totalAcc" label="账单本金"></el-table-column>
            <el-table-column prop="totalBill" label="账单总计"></el-table-column>
            <el-table-column prop="billLength" label="账单数量"></el-table-column>
            <el-table-column prop="create_date" label="创建日期">
                <template v-slot="{row}">
                    {{ moment(row.create_date).format(THE_MOMENT_YYMMDD_HHMMSS) }}
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column align="center" label="操作">
                <template v-slot="{row}">
                    <el-button @click="onClickDetail(row, '查看')" type="text">
                        查看
                    </el-button>
                    <el-button @click="onClickDetail(row, '编辑')" type="text">
                        编辑
                    </el-button>
                    <el-button :disabled="!isOperation" @click="handleShowDeleteDialog(row)" type="text">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            @change="onChangePage"
        />
        <FunctionDialog
            :title="title"
            @on-ok="getList"
            :visible.sync="visibleDetail"
            :data-source="dataSourceDetail"
        ></FunctionDialog>
        <TheElDialog title="删除用户" :visible.sync="dialogVisible">
            <span>你确定删除 {{ currentRow.name }} 吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="dialogLoading" @click="dialogVisible = false">取 消</el-button>
                <el-button :disabled="dialogLoading" type="primary" @click="onClickOkUpdate(currentRow)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
    </LayoutWrap>
</template>
<script>
import {formInputWidth} from '@/styles/variables.scss';
import {getBillPlatforms, deleteBillPlatform} from '@/api/bill';
import {mixinIsOperation} from '@/mixins';
import {mapGetters} from 'vuex';
import FunctionDialog from '@/views/bill/platform/FunctionDialog';
import {BASIC_MONEY, THE_MOMENT_YYMMDD_HHMMSS} from '@/utils/constant';
import moment from 'moment';
const dataSourceDefault = {};
export default {
    name: 'bill-platformu',
    mixins: [mixinIsOperation],
    components: {FunctionDialog},
    data() {
        return {
            moment,
            THE_MOMENT_YYMMDD_HHMMSS,
            BASIC_MONEY,
            formInputWidth,
            // 检索数据
            formSearch: {
                keyName: 'name',
                keyValue: '',
                pageSize: 10,
                page: 1,
                count: 0
            },
            keyOptions: [
                {label: 'name', value: 'name', disabled: false},
                {label: 'remark', value: 'remark', disabled: false}
            ],
            isLoading: false,
            visibleDetail: false,
            dataSourceDefault,
            dataSourceDetail: {...dataSourceDefault},
            title: '',

            // 新建用户弹窗
            userDialogVisible: false,
            // 编辑用户
            userDialogVisibleEdit: false,
            // 查看详情
            userDialogVisibleDetail: false,
            // 删除用户
            dialogVisible: false,
            // 操作用户
            currentRow: {},
            // 删除用户loading
            dialogLoading: false,
            // 添加用户
            dataSourceAdd: {},
            // 编辑用户
            dataSourceEdit: {},
            // 列表数据
            tableData: [],
            multipleSelection: []
        };
    },
    computed: {
        ...mapGetters({
            isMobile: 'app/isMobile'
        })
    },
    created() {
        this.getList();
    },
    methods: {
        handleSelectionChange(value) {
            this.visibleUpdate = false;
            this.multipleSelection = value;
        },
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];

            const types = ['money_total', 'money_used'];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => {
                    if (types.includes(column.property)) {
                        return Number(item[column.property] / BASIC_MONEY);
                    }
                    return Number(item[column.property]);
                });
                if (!values.some(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr * BASIC_MONEY;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = sums[index] / BASIC_MONEY;
                } else {
                    sums[index] = 'N/A';
                }
            });

            return sums;
        },
        resetForm(formSearch) {
            // this.$refs[formSearch].resetFields();
            const {keyName, keyValue, page, pageSize} = this.$options.data().formSearch;
            this.formSearch = {...this.formSearch, keyName, keyValue, page, pageSize};
        },
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        // 搜索
        handleSearch() {
            this.formSearch = {...this.formSearch, page: 1, pageSize: 10};
            this.getList();
        },
        // 获取列表数据
        getList() {
            this.isLoading = true;
            const {keyName, keyValue, pageSize, page} = this.formSearch;

            const newItem = {
                pageSize,
                page
            };
            if (keyName === 'name' && keyValue) {
                newItem.name = keyValue;
            }
            if (keyName === 'remark' && keyValue) {
                newItem.remark = keyValue;
            }

            getBillPlatforms(newItem)
                .then(({data: res}) => {
                    if (res.status === 200) {
                        const {data, count, page, pageSize} = res;
                        this.tableData = data.map(item => {
                            if (Array.isArray(item.bills)) {
                                item.billLength = item.bills.length;
                                const {total_all: totalBill, total: totalAcc} = item.bills.reduce(
                                    (sum, acc) => {
                                        sum.total_all = sum.total_all + acc.total_all;
                                        sum.total = sum.total + acc.total;
                                        return sum;
                                    },
                                    {total_all: 0, total: 0}
                                );
                                item.totalAcc = totalAcc / BASIC_MONEY;
                                item.totalBill = totalBill / BASIC_MONEY;
                            }
                            return item;
                        });
                        this.formSearch = {...this.formSearch, page, pageSize, count};
                    }
                })
                .finally(() => {
                    this.isLoading = false;
                });
        },
        onClickDetail(row, title) {
            this.title = title;
            this.visibleDetail = true;
            this.dataSourceDetail = {...row};
        },
        // 批量修改
        onClickOkUpdate(row) {
            this.dialogLoading = true;
            deleteBillPlatform(row._id)
                .then(res => {
                    this.getList();
                    this.dialogVisible = false;
                    this.$message({showClose: true, type: 'success', message: '修改成功'});
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: '修改失败'});
                    console.error(error);
                })
                .finally(() => {
                    this.dialogLoading = false;
                });
        },
        // 弹出删除弹窗
        handleShowDeleteDialog(row) {
            // 展示删除弹窗
            this.dialogVisible = true;
            this.currentRow = row;
        }
    }
};
</script>

<style lang="scss" scoped>
// .auth {
// }
</style>
